package com.HooDee.netty.thirdDemo;

import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.channel.group.ChannelGroup;
import io.netty.channel.group.DefaultChannelGroup;
import io.netty.util.concurrent.EventExecutor;
import io.netty.util.concurrent.GlobalEventExecutor;

import java.util.Map;
import java.util.UUID;

/**
 * Package: com.HooDee.netty.secondeDemo
 * Description：
 * Author: 蒋豪
 * Date:  2021.09.10 22:01
 * Modified By:
 */
public class MyChatServerHandler extends SimpleChannelInboundHandler<String> {
    // netty自带的通道组：用于保存一个一个的channel
    private static ChannelGroup channelGroup = new DefaultChannelGroup(GlobalEventExecutor.INSTANCE);
    /**
     * 服务端接收任意客户端的消息的时候进入此方法
     * @param ctx
     * @param msg 返回过来的参数对象
     * @throws Exception
     */
    @Override
    protected void channelRead0(ChannelHandlerContext ctx, String msg) throws Exception {
         System.out.println(ctx.channel().remoteAddress() + ", " + msg);
         // 发送数据的连接
         Channel channel = ctx.channel();
         // 在channelGroup中找到自己
        channelGroup.forEach(p -> {
            if (p != channel) {
                p.writeAndFlush(channel.remoteAddress() + "：" + msg + "\n");
            } else {
                p.writeAndFlush("【自己】：" + msg + "\n");
            }
        });
         // 向客户发送消息
         ctx.channel().writeAndFlush("来之服务端的消息："+ UUID.randomUUID());
    }

    /**
     * 连接建立
     * @param ctx
     * @throws Exception
     */
    @Override
    public void handlerAdded(ChannelHandlerContext ctx) throws Exception {
        // 通道
        Channel channel = ctx.channel();
        // 先广播 后加入
        channelGroup.writeAndFlush("【服务器】- IP地址为：" + channel.remoteAddress() + "加入\n");
        channelGroup.add(channel);
    }

    /**
     * 连接断
     * @param ctx
     * @throws Exception
     */
    @Override
    public void handlerRemoved(ChannelHandlerContext ctx) throws Exception {
        Channel channel = ctx.channel();
        // 可写可不写，channelGroup 会自动调用
        // channelGroup.remove(channel);
        channelGroup.writeAndFlush("【服务器】- IP地址为：" + channel.remoteAddress() + "离开\n");
    }

    /**
     * 表示该链接处于活动状态
     * @param ctx
     * @throws Exception
     */
    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        Channel channel = ctx.channel();
        System.out.println(channel.remoteAddress() + "上线了！！！");
    }

    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        Channel channel = ctx.channel();
        System.out.println(channel.remoteAddress() + "下线了！！！");
    }

    /**
     * 发生异常
     * @param ctx
     * @param cause
     * @throws Exception
     */
    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        cause.printStackTrace();
        ctx.close();
    }
}
